package test;

import java.util.ArrayList;

public class ExecuteOperationExpression {
	final static String OPERATORS = "+-*/=";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String oprExp = "7 - 3 * 2 - 8 / 3 - 9 * 4 + 3 / 2 + 5 + 6 * 3 * 3";
		System.out.println(oprExp);
		// Analysis
		String[] tmps = oprExp.split(" ");
		for(String s : tmps) {
			System.out.print(s + ", ");
		}
		System.out.println();

		// operators and numbers
		ArrayList<Double> numbers = new ArrayList<>();
		StringBuilder operators = new StringBuilder();

		for(String s : tmps) {
			if(OPERATORS.contains(s)) {
				operators.append(s);
			}
			else {
				numbers.add(Double.valueOf(s));
			}
		}

		// test
		System.out.println(operators);

		for(Double l : numbers) {
			System.out.print(l + ", ");
		}
		System.out.println();

		// Calculate
		if(operators.charAt(operators.length() - 1) == '=') {
			operators.deleteCharAt(operators.length() - 1);
		}

		for(int i = 0; i < operators.length(); i++) {
			if(operators.charAt(i) == '*') {
				numbers.set(i, (numbers.get(i) * numbers.get(i + 1)));
				i = calculateHelper(i, operators, numbers);
			}
			else if(operators.charAt(i) == '/') {
				numbers.set(i, (numbers.get(i) / numbers.get(i + 1)));
				i = calculateHelper(i, operators, numbers);
			}
		}

		for(int i = 0; i < operators.length(); i++) {
			if(operators.charAt(i) == '+') {
				numbers.set(i, (numbers.get(i) + numbers.get(i + 1)));
				i = calculateHelper(i, operators, numbers);
			}
			else if(operators.charAt(i) == '-') {
				numbers.set(i, (numbers.get(i) - numbers.get(i + 1)));
				i = calculateHelper(i, operators, numbers);
			}
		}

		System.out.println(String.valueOf(numbers.get(0)));
	}

	static public int calculateHelper(int i, StringBuilder operators, ArrayList<Double> numbers) {
		operators.deleteCharAt(i);
		numbers.remove(i + 1);

		return i - 1;
	}

}
